// src/page/HomePage.tsx
import React, { useContext, useEffect, useState } from 'react'
import { Layout, Menu, theme, Dropdown, Avatar, Card, Row, Col, Typography, Statistic } from 'antd'
import {
    ShoppingCartOutlined,
    UserOutlined,
    SafetyCertificateOutlined,
    CustomerServiceOutlined,
    NotificationOutlined,
    BarChartOutlined,
} from '@ant-design/icons'
import { useNavigate, useLocation } from 'react-router-dom'
import { Outlet } from 'react-router-dom'
import UserContext from '../context/UserContext'
import { fileService } from '../api/service/FileService' // 添加导入

const { Header, Sider, Content } = Layout
const { Title } = Typography

const HomePage: React.FC = () => {
    const navigate = useNavigate()
    const location = useLocation()
    const userContext = useContext(UserContext)
    const [avatarUrl, setAvatarUrl] = useState<string | null>(null) // 添加状态管理头像URL

    const {
        token: { colorBgContainer },
    } = theme.useToken()

    // 获取用户头像URL
    useEffect(() => {
        const fetchAvatarUrl = async () => {
            if (userContext?.userInfo?.avatar_addr) {
                try {
                    const fileUrl = await fileService.getDownloadUrl(userContext.userInfo.avatar_addr);
                    setAvatarUrl(fileUrl.url || null);
                } catch (error) {
                    console.error('获取头像失败:', error);
                    setAvatarUrl(null);
                }
            } else {
                setAvatarUrl(null);
            }
        };

        fetchAvatarUrl();
    }, [userContext?.userInfo?.avatar_addr]);

    // 根据当前路径确定选中的菜单项
    const getSelectedKey = () => {
        switch (location.pathname) {
            case '/dashboard':
                return 'dashboard'
            case '/products':
                return 'products'
            case '/users':
                return 'users'
            case '/permissions':
                return 'permissions'
            case '/customer-service':
                return 'customer-service'
            case '/advertisements':
                return 'advertisements'
            default:
                return 'dashboard'
        }
    }

    // 处理用户登出
    const handleLogout = () => {
        if (userContext) {
            userContext.logout()
            navigate('/login')
        }
    }

    // 用户菜单项
    const userMenuItems = [
        {
            key: 'logout',
            label: '退出登录',
            onClick: handleLogout
        }
    ]

    // 快捷操作项
    const quickActions = [
        {
            title: '用户管理',
            icon: <UserOutlined style={{ fontSize: '24px', color: '#1890ff' }} />,
            path: '/users',
            color: '#1890ff'
        },
        {
            title: '广告管理',
            icon: <NotificationOutlined style={{ fontSize: '24px', color: '#52c41a' }} />,
            path: '/advertisements',
            color: '#52c41a'
        },
        {
            title: '数据统计',
            icon: <BarChartOutlined style={{ fontSize: '24px', color: '#722ed1' }} />,
            path: '/dashboard',
            color: '#722ed1'
        },
        {
            title: '商品管理',
            icon: <ShoppingCartOutlined style={{ fontSize: '24px', color: '#fa8c16' }} />,
            path: '/products',
            color: '#fa8c16'
        }
    ];

    return (
        <Layout style={{ minHeight: '100vh' }}>
            <Sider
                style={{
                    overflow: 'auto',
                    height: '100vh',
                    position: 'fixed',
                    left: 0,
                    top: 0,
                    bottom: 0
                }}
            >
                <div style={{
                    height: '64px',
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    color: 'white',
                    fontSize: '18px',
                    fontWeight: 'bold',
                    background: 'rgba(0, 0, 0, 0.2)'
                }}>
                    管理系统
                </div>
                <Menu
                    theme="dark"
                    mode="inline"
                    selectedKeys={[getSelectedKey()]}
                    onClick={({ key }) => {
                        switch (key) {
                            case 'dashboard':
                                navigate('/dashboard')
                                break
                            case 'products':
                                navigate('/products')
                                break
                            case 'users':
                                navigate('/users')
                                break
                            case 'permissions':
                                navigate('/permissions')
                                break
                            case 'customer-service':
                                navigate('/customer-service')
                                break
                            case 'advertisements':
                                navigate('/advertisements')
                                break
                            default:
                                navigate('/')
                        }
                    }}
                    items={[
                        { key: 'dashboard', icon: <ShoppingCartOutlined />, label: '仪表盘' },
                        { key: 'products', icon: <ShoppingCartOutlined />, label: '商品管理' },
                        { key: 'users', icon: <UserOutlined />, label: '用户管理' },
                        { key: 'permissions', icon: <SafetyCertificateOutlined />, label: '权限管理' },
                        { key: 'customer-service', icon: <CustomerServiceOutlined />, label: '客服管理' },
                        { key: 'advertisements', icon: <NotificationOutlined />, label: '广告管理' },
                    ]}
                />
            </Sider>
            <Layout
                style={{
                    marginLeft: 200,
                    minHeight: '100vh'
                }}
            >
                <Header style={{ padding: '0 24px', background: colorBgContainer, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                    <div></div>
                    {userContext?.userInfo && (
                        <Dropdown menu={{ items: userMenuItems }} placement="bottomRight">
                            <div style={{ display: 'flex', alignItems: 'center', cursor: 'pointer' }}>
                                <Avatar
                                    icon={<UserOutlined />}
                                    src={avatarUrl || userContext.userInfo.avatar_addr} // 使用获取到的URL或原始地址
                                />
                                <span style={{ margin: '0 8px', color: 'rgba(0,0,0,0.85)' }}>
                                    {userContext.userInfo.nickname || userContext.userInfo.username}
                                </span>
                            </div>
                        </Dropdown>
                    )}
                </Header>
                <Content
                    style={{
                        margin: '24px 16px',
                        padding: 24,
                        background: colorBgContainer,
                        overflow: 'auto',
                        minHeight: 'calc(100vh - 112px)'
                    }}
                >
                    {/* 如果是仪表盘路径，显示仪表盘内容 */}
                    {location.pathname === '/' || location.pathname === '/dashboard' ? (
                        <div>
                            <Title level={3}>仪表盘</Title>

                            {/* 统计卡片 */}
                            <Row gutter={16} style={{ marginBottom: 24 }}>
                                <Col span={6}>
                                    <Card>
                                        <Statistic
                                            title="商品总数"
                                            value={120}
                                            prefix={<ShoppingCartOutlined />}
                                        />
                                    </Card>
                                </Col>
                                <Col span={6}>
                                    <Card>
                                        <Statistic
                                            title="用户总数"
                                            value={850}
                                            prefix={<UserOutlined />}
                                        />
                                    </Card>
                                </Col>
                                <Col span={6}>
                                    <Card>
                                        <Statistic
                                            title="待处理客服"
                                            value={8}
                                            prefix={<CustomerServiceOutlined />}
                                        />
                                    </Card>
                                </Col>
                                <Col span={6}>
                                    <Card>
                                        <Statistic
                                            title="广告数量"
                                            value={12}
                                            prefix={<NotificationOutlined />}
                                        />
                                    </Card>
                                </Col>
                            </Row>

                            {/* 快捷操作 */}
                            <Card title="快捷操作">
                                <Row gutter={16}>
                                    {quickActions.map((action, index) => (
                                        <Col span={6} key={index}>
                                            <Card
                                                hoverable
                                                onClick={() => navigate(action.path)}
                                                style={{ textAlign: 'center', cursor: 'pointer' }}
                                            >
                                                {action.icon}
                                                <h3 style={{ marginTop: 16, color: action.color }}>{action.title}</h3>
                                            </Card>
                                        </Col>
                                    ))}
                                </Row>
                            </Card>

                            {/* 最近活动 */}
                            <Card title="最近活动" style={{ marginTop: 24 }}>
                                <p>暂无最新活动</p>
                            </Card>
                        </div>
                    ) : (
                        <Outlet />
                    )}
                </Content>
            </Layout>
        </Layout>
    )
}

export default HomePage
